package com.demo.common.excel;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.common.cache.CacheService;
import com.demo.common.utils.CacheKeyConstants;
import com.demo.entity.SysRole;
import com.demo.service.SysRoleService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * excel转换器注册器，没有自定义转换则不需要加
 */
@Component
public class ExcelConvertRegister implements InitializingBean {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private CacheService cacheService;

    @Override
    public void afterPropertiesSet() throws Exception {
        //localDateTime序列化
        ExcelUtils.registerExportConvert(ExcelConvertName.LOCAL_DATE_TIME_SERIALIZABLE,(time)->{
            if(time instanceof LocalDateTime){
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                return dateTimeFormatter.format((LocalDateTime)time);
            }
            return time;
        });
        //角色名转id
        ExcelUtils.registerImportConvert(ExcelConvertName.ROLE_NAME_TO_ID,(roleName)->{
            String key=CacheKeyConstants.ROLE_NAME_ID+roleName;
            Integer roleId=cacheService.getCache(key);
            if(roleId==null){
                SysRole one = sysRoleService.getOne(new QueryWrapper<SysRole>().eq(SysRole.ROLE_NAME, roleName));
                if(one==null){
                    roleId=-1;
                }else{
                    roleId=one.getId();
                }
                cacheService.setCache(key,roleId,60);
            }
            return roleId;
        });
        //角色id转name
        ExcelUtils.registerExportConvert(ExcelConvertName.ROLE_ID_TO_NAME,(roleId)->{
            String key=CacheKeyConstants.ROLE_ID_NAME+roleId;
            String roleName=cacheService.getCache(key);
            if(roleName==null){
                SysRole one = sysRoleService.getById((Integer)roleId);
                if(one==null){
                    roleName="id为"+roleId+"的角色不存在";
                }else{
                    roleName=one.getRoleName();
                }
                cacheService.setCache(key,roleName,60);
            }
            return roleName;
        });

    }

}
